﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IISLogAnalysis.Config;
using IISLogAnalysis.Business;

namespace IISLogAnalysis.UI.WinFrom
{
    public partial class Form1 : Form
    {
        //fields
        private List<string> listFiles = new List<string>();
        private string paramOfCommon = "-i:w3c -o:tsv -oSeparator:space ";
        private string tempResultFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "result.log");
        private char split = ' ';

        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            openFileDialog.FileOk += new CancelEventHandler(openFileDialog_FileOk);
            //openFileDialog.Multiselect = true;
            openFileDialog.ShowDialog();
        }

        void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            if (openFileDialog.FileNames.Length > 0)
            {
                openFileDialog.FileNames.ToList().ForEach(x => { listFiles.Add(x); tbFiles.AppendText(x + Environment.NewLine); });
            }
        }

        private void btnClearFiles_Click(object sender, EventArgs e)
        {
            tbFiles.Text = string.Empty;
            listFiles.Clear();
        }

        private void btnAnalysisMaxIP_Click(object sender, EventArgs e)
        {
            if (!CheckIsSelectedFile()) return;

            string query = string.Format("select c-ip,count(*) as [count] into {0} from {1} group by c-ip order by [count] desc", tempResultFilePath, listFiles[0]);
            RunLogParserExe.RunLogParser(query, paramOfCommon);
            //RunLogParserExe.RunNotepad(tempResultFilePath);
            GenerateDataGridView(RunLogParserExe.ReadResult(tempResultFilePath));
        }

        private void DisplayResult(List<string> result)
        {
            //result.ForEach(x => { tbResult.AppendText(x + Environment.NewLine); });
        }

        private void btnCustomSql_Click(object sender, EventArgs e)
        {
            if (!CheckIsSelectedFile()) return;

            string query = tbQuery.Text.Replace("from", " into " + tempResultFilePath + " from").Replace("{0}", listFiles[0]);
            RunLogParserExe.RunLogParser(query, paramOfCommon);
            //RunLogParserExe.RunNotepad(tempResultFilePath);
            GenerateDataGridView(RunLogParserExe.ReadResult(tempResultFilePath));
        }

        private bool CheckIsSelectedFile()
        {
            if (listFiles.Count == 0)
            {
                MessageBox.Show("先选择日志文件");
                return false;
            }
            return true;
        }

        private void btnMaxBrowser_Click(object sender, EventArgs e)
        {
            if (!CheckIsSelectedFile()) return;

            string query = string.Format("select [cs(User-Agent)] as user-agent,count(*) as [count] into {0} from {1} group by [cs(User-Agent)]  order by [count] desc", tempResultFilePath, listFiles[0]);
            RunLogParserExe.RunLogParser(query, paramOfCommon);
            //RunLogParserExe.RunNotepad(tempResultFilePath);
            GenerateDataGridView(RunLogParserExe.ReadResult(tempResultFilePath));
        }

        private void btnMaxPage_Click(object sender, EventArgs e)
        {
            if (!CheckIsSelectedFile()) return;

            string query = string.Format("select cs-uri-stem as page-path,count(*) as [count] into {0} from {1} group by [cs-uri-stem]  order by [count] desc", tempResultFilePath, listFiles[0]);
            RunLogParserExe.RunLogParser(query, paramOfCommon);
            //RunLogParserExe.RunNotepad(tempResultFilePath);

            GenerateDataGridView(RunLogParserExe.ReadResult(tempResultFilePath));
        }



        private void GenerateDataGridView(List<string> list)
        {
            dgv.Columns.Clear();
            dgv.Rows.Clear();

            if (list.Count > 1)
            {
                //header
                GenerateDataGridViewHeader(list[0]);
                string[] headers = list[0].Split(split);
                //rows
                for (int i = 1; i < list.Count; i++)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    string[] currentRow = list[i].Split(split);
                    for (int j = 0; j < headers.Length; j++)
                    {
                        DataGridViewTextBoxCell tbc=new DataGridViewTextBoxCell();
                        tbc.Value = currentRow[j];
                        row.Cells.Add(tbc);
                    }

                    dgv.Rows.Add(row);
                }
            }
        }

        private void GenerateDataGridViewHeader(string str)
        {
            if (string.IsNullOrEmpty(str) == false)
            {
                foreach (var item in str.Split(split))
                {
                    //DataGridViewColumn c = new DataGridViewColumn();
                    //DataGridTextBoxColumn c = new DataGridTextBoxColumn();
                    //c.HeaderText = item;
                    dgv.Columns.Add(item, item);
                }
            }
        }
    }
}
